﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Text;

namespace WebLog.Db
{
    public class KeyValueRepository
    {
        static class Inner
        {
            internal static readonly KeyValueRepository keyValueRepository = new KeyValueRepository();
        }
        SQLiteHelper sQLiteHelper = SQLiteHelper.GetInstance();
        static internal KeyValueRepository GetInstance() => Inner.keyValueRepository;
        public T Get<T>(string keyName, T defVal = default(T))
        {
            var result = defVal;
            DataTable dt = null;
            try
            {
                dt = sQLiteHelper.GetDataTable(@"select Value from KeyValues where (Key=@Key) LIMIT 0, 1", sQLiteParameters: new SQLiteParameter("@Key", keyName));
            }
            catch (Exception ex)
            {
            }
            if (dt?.Rows.Count == 1)
            {
                try
                {
                    result = JsonConvert.DeserializeObject<T>(dt.Rows[0][0].ToString());
                    if (result == null && defVal != null)
                    {
                        Set<T>(keyName, defVal);
                        result = defVal;
                    }
                }
                catch (Exception)
                {
                }
            }
            else Set<T>(keyName, defVal);
            return result;
        }
        public bool Set<T>(string keyName, T val = default(T))
        {
            try
            {
                return sQLiteHelper.ExecuteNonQuery(@"delete from KeyValues where (Key=@Key);insert into KeyValues(Key,Value) values(@Key, @Value)", true,
                    new SQLiteParameter("@Key", keyName), new SQLiteParameter("@Value", JsonConvert.SerializeObject(val))) > 0;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
